import HttpUtils from '../HttpUtils/HttpUtils';
var flag = false;
// 获取当前时间戳
var timestamp = Date.parse(new Date()) / 1000;
let globalData = getApp().globalData;
Page({
    ...HttpUtils.func,
    data: {
      indicatorDots: true,  // 显示指示点
      autoplay: true,       // 自动播放
      interval: 4000,       // 播放间隔时间
      duration: 500,        // 滑动动画时长
      parentId: 8015,
      vshow: true,          // 不显示底部图片
      folderCode: 0,        // 内容代码
      pageIndex: 1,         // 显示页码
      pageItems: 3,         // 页数
      totalPages: 0,        // 总页数
      columnFolderId: 8003,
      figures: [{
        figureIndex: 1,
        url: '',
        iconId: 0,
        iconUrl: '',
        figureDesc: ''
      }],
      columnFolderList: [], // 栏目推荐
      columnList: [],       // 中间栏目导航条
      contentList: [],      // 栏目下内容列表
      msgList: [],          // 加载导航栏消息
      msgSrc: '',
      noMsg: ''
  },
  /**
   *  中间四个菜单的跳转函数
   */
  forwardSubPages: function(e) {
      let name = e.currentTarget.dataset.name,
          pageName = '/pages/' + name + '/' + name;

      wx.navigateTo({
        url: pageName
      });
  },
  // 页面加载
  onLoad(query) {
      let that = this;

      wx.getSystemInfo({ // 设置手机屏幕宽度
        success: (res) => {
          console.log(res.screenWidth + "--" + res.screenHeight)
          console.log("设置手机屏幕宽度" + res.windowWidth)
          console.log("设置手机屏幕高度" + res.windowHeight)
          this.setData({
            screenHeight: res.windowHeight
          })
        }
    });


      let userId = getApp().globalData.userId;
      if (userId == 0) {
          console.log('call back0');
          getApp().userInfoReadyCallback = res => {
              console.log('call back2');
              //如果服务时间 到期 則弹框
            //   var sysTime = that.formatDate("yyyy-MM-dd hh:mm:ss", new Date());
            //   if (getApp().globalData.userId != 0 && new Date(sysTime.replace(/-/g, '/')).getTime() >=
            //       new Date(getApp().globalData.serviceStopTime.replace(/-/g, '/')).getTime()) {
            //       wx.reLaunch({
            //           url: "../moneyPop/moneyPop?showMoneyPop=" + true
            //       })
            //   }
              if (getApp().globalData.userId != 0) {
                  //加载导航栏消息
                  that.loadMsg();
                  //加载轮播图 
                  that.loadFigures();

                  //加载中间栏目导航条	
                  that.loadColumnList();

                  //加载栏目推荐
                  that.loadColumnFolderQuery();
              }
          }
      }

      if (that.data.isPullDown) {
          //加载导航栏消息
          that.loadMsg();
          //加载轮播图 
          that.loadFigures();

          //加载中间栏目导航条	
          that.loadColumnList();

          //加载栏目推荐
          that.loadColumnFolderQuery();
      }


    
  },
  //加载导航栏消息
  loadMsg: function() {  
      let newUrl = globalData.dangjianUrl + '/member/userMsgList',
          params = {
              'pageIndex': '1',
              'pageItems': '2',
              'msgType': '',
              'msgTitle': '',
              'read': ''
          },
          param = JSON.stringify(params),
          result = '',
          msgs = '',
          msgList = [],
          msg = '',
          json = {},
          sysTime = '',
          times = '',
          h = '', d = '', m = '';
        
          this.httpGet(newUrl, param, "消息列表加载失败").then((respData) => {
              result = respData.data.result.code;
              if (+result == 1) {
                   msgs = respData.data.msgs.msg;
                   msgList = [];

              for (var index in msgs) {
                  msg = msgs[index];
                  json.msgId = msg.msgId;
                  json.msgTitle = msg.msgTitle;
                  json.msgContent = msg.msgContent;
                  sysTime = this.formatDate("yyyy-MM-dd hh:mm:ss", new Date());
                  times = (new Date(sysTime.replace(/-/g, '/')).getTime() - new Date(msg.publishTime.replace(/-/g, '/')).getTime());
                  d = parseInt(times / (1000 * 60 * 60 * 24));
                  h = parseInt(times / (1000 * 60 * 60));
                  m = parseInt(times / (1000 * 60));
                  if (h <= 0) {
                    json['publishTime'] = m + '分钟前'
                  } else if (h >= 24) {
                    json['publishTime'] = d + '天前'
                  } else {
                    json['publishTime'] = h + '小时前'
                  }
            json['isRead'] = msg.isRead;
            //按钮
            json['buttonName'] = "删除";
            json['deleteShow'] = "deleteHide";
            msgList.push(json);
          }
          console.log('消息列表');
          console.log(msgList);
          this.setData({
            'msgList': msgList,
            'noMsg': '您的信箱暂无其他消息！',
            'msgSrc': '../../img/msg_point.png'
          });
        } else {
          this.showPageMsg('alert', respData.data.result.description);
        }
      }
    );
  },
  //加载栏目推荐
  loadColumnFolderQuery: function(type) {
      let newUrl = globalData.dangjianUrl + '/content/relativeFolderQuery',
          params = {
            'pageIndex': '1',
            'pageItems': '10',
            'code': this.data.columnFolderId,
            'siteCode': globalData.siteCode
          },
          param = JSON.stringify(params),
          result = '',
          folders = [],
          length = '';
   
          this.httpGet(newUrl, param, '子栏目查询加载失败').then((respData) => {
             result = respData.data.result.code;
             if (+result == 1) {
             folders = respData.data.folders.folder;
             // folders =	folders.splice(2.4)
             length = Math.ceil(folders.length / 4)
                 this.setData({
                    'columnFolderList': folders,
                    'height': length > 1 ? length * 200 + 'rpx' : '260rpx',
                 });
                 type && wx.stopPullDownRefresh();
        } else {
          this.showPageMsg('alert', respData.data.result.description);
        }
      }
    );
  },

  //点击轮播图跳转
  figureClick: function(e) {
      let url = e.currentTarget.dataset.url == "" ? "https://www.baidu.com" : e.currentTarget.dataset.url,
          regex = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;

      if (regex.test(url)) {
        wx.navigateTo({
          url: '/pages/outerLink/outerLink?hrefLink=' + url
        });
      } else {
        wx.showToast({
          title: '跳转地址不合法,请检查后台地址设置是否正确'
        });
      }
  },

  //加载轮播图
  loadFigures: function() {
      let newUrl = globalData.dangjianUrl + "/party/corpCarouselFifure",
          params = {};
          params = JSON.stringify(params);

      this.httpGet(newUrl, params, "轮播图加载失败").then((respData) => {
        var result = respData.data.result.code;
        if (result == 1) {
          var figures = respData.data.figures;
          this.setData({
            'figures': figures
          });
        } else {
          this.showPageMsg("alert", respData.data.result.description);
        }
      }
    );
  },
  //测试 内容栏目查询
  loadFolderQuery: function(e) {
      let newUrl = globalData.dangjianUrl + '/content/folderQuery';
      let params = {};
      
      params["code"] = this.data.parentId + '';
      params["siteCode"] = getApp().globalData.siteCode + "";
      params = JSON.stringify(params);

    this.httpGet(newUrl, params, '栏目查询失败').then((respData) => {
        var result = respData.data.result.code;
        if (result == 1) {
            this.showPageMsg("alert", respData.data.result.description);
        } else {
            this.showPageMsg("alert", respData.data.result.description);
        }
      }
    );
  },
  //加载中间栏目导航条
  loadColumnList: function() {
      let newUrl = globalData.dangjianUrl + '/content/relativeFolderQuery';
      let params = {};

      params["pageIndex"] = '1';
      params["pageItems"] = '10';
      params["code"] = this.data.parentId + '';
      params["siteCode"] = getApp().globalData.siteCode + '';
      params = JSON.stringify(params);

      this.httpGet(newUrl, params, '子栏目查询加载失败').then((respData) => {
        var result = respData.data.result.code;
        if (result == 1) {
            var folders = respData.data.folders.folder;
            var firstCode = folders[0].code;
            this.setData({
                'columnList': folders,
                'folderCode': firstCode
            });
            this.loadContentList(firstCode);
        } else {
            this.showPageMsg('alert', respData.data.result.description);
        }
      }
    );
  },
  //加载栏目下内容
  loadContentList: function(e) {
      var folderCode = 0;
      if ("string" == typeof(e)) {
          folderCode = e;
      } else {
      if (e != undefined) {
        folderCode = e.currentTarget.dataset.code; //表示从页面上点击过来de,是一个对象
        this.setData({
          "pageIndex": 1,
        })
      } else {
        folderCode = this.data.folderCode; //表示从页面上拉加载的 直接获取
        flag = false;
      }
    }
    console.log(folderCode + "," + getApp().globalData.siteCode + "," + this.data.pageIndex + "," + this.data.pageItems)
    var newUrl = getApp().globalData.dangjianUrl + "/content/relativeContentQuery";
    var params = {};
    params["pageIndex"] = this.data.pageIndex + "";
    params["pageItems"] = this.data.pageItems + "";
    params["code"] = folderCode + "";
    params["siteCode"] = getApp().globalData.siteCode + "";
    params = JSON.stringify(params);

    this.httpGet(newUrl, params, "栏目下内容加载失败").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          var contents = respData.data.contents;
          var totalPages = contents.totalPages;
          var pageIndex = contents.pageIndex;
          contents = contents.content;
          var contentList = [];
          for (var index in contents) {
            var content = contents[index];
            var json = {};
            var thumbnail = content.thumbnail;
            if (null == thumbnail || "" == thumbnail) {
              var imageFiles = content.imageFiles;
              for (var j in imageFiles) {
                if (imageFiles[j].type == getApp().globalData.imageType) {
                  thumbnail = imageFiles[j].url;
                  break;
                }
              }
            }
            json["name"] = content.name;
            json["publishTime"] = content.publishTime;
            json["url"] = thumbnail;
            json["code"] = content.code;
            json["type"] = content.type;
            json["foldCodes"] = folderCode;
            json["count"] = content.count;
            json["fromNa"] = '' == content.fromNa || "" == content.fromNa ? "华数" : content.fromNa;
            json["folderCode"] = folderCode;
            contentList.push(json);
          }
          var columnList = this.data.columnList;
          for (var index in columnList) {
            var column = columnList[index];
            if (folderCode == column.code) {
              column["className"] = 'titOn';
            } else {
              column["className"] = '';
            }
          }
          if (e == undefined) {
            var oldContentList = this.data.contentList;
            contentList = oldContentList.concat(contentList); //表示从页面上拉加载的 直接获取
          }
          this.setData({
            'contentList': contentList,
            'columnList': columnList,
            'totalPages': totalPages,
            'pageIndex': pageIndex,
            'vshow': true,
            'currentFolderCode': folderCode
          });
        } else {
          this.showPageMsg("alert", respData.data.result.description);
        }
      }
    );
  },
  //栏目内容详情展示
  articleDetail(e) {
      let folderCode = e.currentTarget.dataset.foldercode,
          type = e.currentTarget.dataset.type,
          code = e.currentTarget.dataset.code,
          name = e.currentTarget.dataset.name,
          detailUrl = this.getUrl(type, code, folderCode, name);

      if (detailUrl.length > 0) {
          wx.navigateTo({
          url: detailUrl
      });
      } else {
         this.showPageMsg("alert", respData.data.result.description);
      }
  },
  //查看更多的跳转
  forwardList: function(e) {
      let folderCode = e.currentTarget.dataset.foldercode,
          currentFolderCode = e.currentTarget.dataset.currentcode;

      wx.navigateTo({
          url: '/pages/news/news?folderCode=' + folderCode + '&currentFolderCode=' + currentFolderCode
      });
  },
  //首页消息提醒跳转
  messageList: function(e) {
    wx.navigateTo({
      url: '/pages/message/message'
    });
  },
  // 页面被拉到底部
  onReachBottom: function(e) {
    let pageIndex = this.data.pageIndex + 1,
        totalPages = this.data.totalPages,
        folderCode = this.data.currentFolderCode;

    if (totalPages >= pageIndex) {
      this.setData({
        'pageIndex': pageIndex,
        'folderCode': folderCode,
      });
      this.loadContentList();
    } else {
      this.setData({
        'vshow': false
      });
    }
  },
  // 页面 下拉刷新
  onPullDownRefresh: function(e) {
    let that = this; 
    // that.setData({
    //   pageIndex: 1,
    //   contentList: [],
    // });
    
     //加载导航栏消息
     that.loadMsg();
     //加载轮播图 
     that.loadFigures();

     //加载中间栏目导航条	
     that.loadColumnList();

     //加载栏目推荐
     that.loadColumnFolderQuery(!0);
  },
  //获取当前滚动条位置  
  onPageScroll: function(e) {
    //滚动条<360  赋值为1
    if (e.scrollTop < '360' && flag) {
      this.setData({
        "pageIndex": 1,
      })
    }
  },
  //底部点击事件
  back_top: function(e) {
      if (wx.pageScrollTo) {
         wx.pageScrollTo({
         scrollTop: 0
      })
      this.setData({
        // "pageIndex": 1, 
        'vshow': true
      })
    } else {
      wx.showToast({
        title: '该内容类型详情页暂未开发'
      });
    }
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: '党建e应用',
      desc: '微信党建e应用',
      path: 'pages/index/index'
    };
  }
});